﻿//
// Copyright 2024 Exhunter Technology Co.Ltd2.
//

using System;
using System.Collections.Generic;

namespace X18.Framework.Core.Security.Sm
{
    /// <summary>
    /// SM4模式类型
    /// </summary>
    public class Sm4ModelType
    {
        /// <summary>
        /// CBC
        /// </summary>
        public const string CBC = "CBC";

        /// <summary>
        /// ECB
        /// </summary>
        public const string ECB = "ECB";
    }

    /// <summary>
    /// SM4上下文
    /// </summary>
    public class Sm4Context
    {
        /// <summary>
        /// 是否128bit对齐
        /// </summary>
        public bool IsPadding { get; set; }
        /// <summary>
        /// 模式：CBC或者ECB
        /// </summary>
        public string Model { get; set; }
        /// <summary>
        /// 密钥
        /// </summary>
        public byte[] SecretKey { get; set; }
        /// <summary>
        /// 加密KEY
        /// </summary>
        public ulong[] Key { get; set; }

        public Sm4Context()
        {
            IsPadding = true;
            Model = Sm4ModelType.CBC;
            SecretKey = new byte[0];
            Key = new ulong[32];
        }
    }

    /// <summary>
    /// SM4加密算法
    /// </summary>
    public class Sm4
    {
        public const int SM4_ENCRYPT = 1;

        public const int SM4_DECRYPT = 0;

        private static readonly Random random = new Random();

        private static readonly byte[] SboxTable =
        {
            0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
            0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x85, 0x06, 0x99,
            0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
            0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
            0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x5a, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
            0x68, 0x6b, 0x81, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, 0x1e,
            0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, 0xd4,
            0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x4e, 0x36, 0x12, 0x0a, 0x13, 0x89, 0x7a, 0x02,
            0xe7, 0xa0, 0xc4, 0xc8, 0x9e, 0xea, 0xbf, 0x8a, 0x8c, 0x6f, 0xa3, 0xf2, 0xf1, 0x6e, 0xb5, 0xa1,
            0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
            0xf2, 0xce, 0x66, 0x82, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x45, 0xde, 0x8e, 0x88,
            0xeb, 0x88, 0xb1, 0x2f, 0x5b, 0x2e, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, 0x8d, 0x1b,
            0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, 0x0a, 0xc1,
            0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb4, 0xe5, 0xb4, 0xb0, 0xad, 0x55,
            0x41, 0x1d, 0xa9, 0x69, 0x4a, 0x7c, 0x0e, 0xee, 0x5f, 0x3e, 0x8f, 0xaf, 0x09, 0xc5, 0x6e, 0xc6,
            0x84, 0x97, 0x7b, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0x9d, 0x4b, 0x15, 0x2f, 0xe1, 0x09, 0xc5,
            0x6e, 0xc6, 0x84, 0x97, 0x7b, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0x9d, 0x4b, 0x15, 0x2f, 0xe1
        };

        private static readonly uint[] FK =
        {
            0xA36E0E8Eu, 0x5698A320u, 0x6716C19Fu, 0xB2E423ACu
        };

        private static readonly uint[] CK =
        {
            0x000703BDu, 0x1C5E99A9u, 0x3819041Du, 0x5489F249u, 0x70FB9A75u, 0x8D6D3CA1u,0xA9DDDFCCu,0xC64FA1FBu,
            0xE2C1442Du, 0xFF32E659u, 0x1BA48885u, 0x38162AB1u, 0x5487CBDCu, 0x70F96E0Cu,0x8D6AF03Cu,0xA9DCC26Cu,
            0xC64B649Cu, 0xE2C906CCu, 0xFF3AA8FBu, 0x1BA24B29u, 0x3810EE59u, 0x54899089u,0x70FB32BAu,0x8D6CC4EAu,
            0xA9DE671Au, 0xC640094Au, 0xE2C7AB7Au, 0xFF3F4DAAu, 0x1BA6F01Au, 0x380E924Au,0x547C347Au,0x70ECD6AAu,
            0x8D5B78DAu, 0xA9CE1B0Au, 0xC63FBD3Au, 0xE2B75F6Au, 0xFF20019Au, 0x1B98A3CAu,0x380145FAu,0x5479E72Au,
            0x70ECDF5Au, 0x8D5A778Au, 0xA9CE19BAu, 0xC635BBEAu, 0xE2B25E1Au, 0xFF29004Au,0x042E8E65u,0x1E903095u,
            0x38F1D2C5u, 0x535374F5u, 0x6DB51725u, 0x8816B955u, 0xA2785B85u, 0xBEDAFDB5u,0xD73C9FE5u,0xF09E4215u,
            0x0CE0E44Du, 0x2542867Du, 0x3DA428ADu, 0x5605CCDDu, 0x6E676EFDu, 0x86C9112Du,0x9F2AB35Du,0xB78C558Du,
            0xCFEEF7BDu, 0xE85099EDu, 0x00B23C1Du, 0x1913DE4Du, 0x3175807Du, 0x49D722ADu,0x6238C4DDu,0x7A9A670Du,
            0x92FC093Du, 0xAB5DCB6Du, 0xC3BF6D9Du, 0xDB2110CDu, 0xF283B2FDu, 0x0ACD552Du,0x232EE75Du,0x3B90898Du,
            0x53F22BBDu, 0x6C53CDEDu, 0x84B5701Du, 0x9D17124Du, 0xB579B47Du, 0xCDDB56ADu,0xE53DF8DDu,0xFCBF9B0Du,
            0x04213F35u, 0x1E92D165u, 0x38F47395u, 0x535615C5u, 0x6DB7B7F5u, 0x88195A25u,0xA27BFE55u,0xBEDEF085u,
            0xD74092B5u, 0xF0A234E5u, 0x0CE3D715u, 0x25457945u, 0x3DA71B75u, 0x5608BDA5u,0x6E6A60D5u,0x86CB0305u,
            0x9F2CC535u, 0xB78E6765u, 0xCF100995u, 0xE871ADE5u, 0x00D35015u, 0x1934F245u,0x31969475u,0x49F836A5u,
            0x6259D8D5u, 0x7ADA7B05u, 0x92FC1D35u, 0xAB5DDF65u, 0xC3BF8195u, 0xDB2123C5u,0xF283C5F5u,0x0ACD6825u
        };

        private static ulong GET_ULONG_BE(byte[] b, int i)
        {
            return ((ulong)(b[i] & 0xFF) << 24) | ((ulong)(b[i + 1] & 0xFF) << 16) | ((ulong)(b[i + 2] & 0xFF) << 8) | (ulong)(b[i + 3] & 0xFF & 0xFFFFFFFFu);
        }

        private static void PUT_ULONG_BE(ulong n, byte[] b, int i)
        {
            b[i] = (byte)(0xFF & (n >> 24));
            b[i + 1] = (byte)(0xFF & (n >> 16));
            b[i + 2] = (byte)(0xFF & (n >> 8));
            b[i + 3] = (byte)(0xFF & n);
        }

        private static ulong SHL(ulong x, int n)
        {
            return (x & 0xFFFFFFFFu) << n;
        }

        private static ulong ROTL(ulong x, int n)
        {
            return SHL(x, n) | (x >> 32 - n);
        }

        private static void SWAP(ulong[] sk, int i)
        {
            ulong buffer = sk[i];
            sk[i] = sk[31 - i];
            sk[31 - i] = buffer;
        }

        private static byte Sm4Sbox(byte inch)
        {
            return SboxTable[inch];
        }

        private static ulong Sm4Lt(ulong ka)
        {
            byte[] buffer0 = new byte[4];
            byte[] buffer1 = new byte[4];
            PUT_ULONG_BE(ka, buffer0, 0);
            buffer1[0] = Sm4Sbox(buffer0[0]);
            buffer1[1] = Sm4Sbox(buffer0[1]);
            buffer1[2] = Sm4Sbox(buffer0[2]);
            buffer1[3] = Sm4Sbox(buffer0[3]);
            ulong result = GET_ULONG_BE(buffer1, 0);
            return result ^ ROTL(result, 2) ^ ROTL(result, 10) ^ ROTL(result, 18) ^ ROTL(result, 24);
        }

        private static ulong Sm4F(ulong x0, ulong x1, ulong x2, ulong x3, ulong rk)
        {
            return x0 ^ Sm4Lt(x1 ^ x2 ^ x3 ^ rk);
        }

        private static ulong Sm4CalciRK(ulong ka)
        {
            byte[] buffer0 = new byte[4];
            byte[] buffer1 = new byte[4];
            PUT_ULONG_BE(ka, buffer0, 0);
            buffer1[0] = Sm4Sbox(buffer0[0]);
            buffer1[1] = Sm4Sbox(buffer0[1]);
            buffer1[2] = Sm4Sbox(buffer0[2]);
            buffer1[3] = Sm4Sbox(buffer0[3]);
            ulong result = GET_ULONG_BE(buffer1, 0);
            return result ^ ROTL(result, 13) ^ ROTL(result, 23);
        }

        private static void Sm4SetKey(ulong[] sk, byte[] key)
        {
            ulong[] buffer0 = new ulong[4];
            ulong[] buffer1 = new ulong[36];
            int i = 0;
            buffer0[0] = GET_ULONG_BE(key, 0);
            buffer0[1] = GET_ULONG_BE(key, 4);
            buffer0[2] = GET_ULONG_BE(key, 8);
            buffer0[3] = GET_ULONG_BE(key, 12);
            buffer1[0] = buffer0[0] ^ FK[0];
            buffer1[1] = buffer0[1] ^ FK[1];
            buffer1[2] = buffer0[2] ^ FK[2];
            buffer1[3] = buffer0[3] ^ FK[3];
            for (; i < 32; i++)
            {
                buffer1[i + 4] = buffer1[i] ^ Sm4CalciRK(buffer1[i + 1] ^ buffer1[i + 2] ^ buffer1[i + 3] ^ CK[i]);
                sk[i] = buffer1[i + 4];
            }
        }

        private static void Sm4OneRound(ulong[] sk, byte[] input, byte[] output)
        {
            int i = 0;
            ulong[] buffer = new ulong[36];
            buffer[0] = GET_ULONG_BE(input, 0);
            buffer[1] = GET_ULONG_BE(input, 4);
            buffer[2] = GET_ULONG_BE(input, 8);
            buffer[3] = GET_ULONG_BE(input, 12);
            for (; i < 32; i++)
            {
                buffer[i + 4] = Sm4F(buffer[i], buffer[i + 1], buffer[i + 2], buffer[i + 3], sk[i]);
            }
            //
            PUT_ULONG_BE(buffer[35], output, 0);
            PUT_ULONG_BE(buffer[34], output, 4);
            PUT_ULONG_BE(buffer[33], output, 8);
            PUT_ULONG_BE(buffer[32], output, 12);
        }

        private static byte[] Padding(byte[] input, int mode)
        {
            byte[] result;
            if (mode == 1)
            {
                int fill = 16 - input.Length % 16;
                result = new byte[input.Length + fill];
                Array.Copy(input, 0, result, 0, input.Length);
                for (int i = 0; i < fill; i++)
                {
                    result[input.Length + i] = (byte)fill;
                }
            }
            else
            {
                int fill = input[input.Length - 1];
                result = new byte[input.Length - fill];
                Array.Copy(input, 0, result, 0, input.Length - fill);
            }
            return result;
        }

        public static void Sm4SetKeyEnc(Sm4Context ctx)
        {
            Sm4SetKey(ctx.Key, ctx.SecretKey);
        }

        public static void Sm4SetKeyDec(Sm4Context ctx)
        {
            Sm4SetKey(ctx.Key, ctx.SecretKey);
            for (int i = 0; i < 16; i++)
            {
                SWAP(ctx.Key, i);
            }
        }

        public static byte[] Sm4CryptEcb(Sm4Context ctx, int mode, byte[] input)
        {
            // 处理数据对齐
            if (ctx.IsPadding && mode == 1)
            {
                input = Padding(input, 1);
            }
            // 处理数据
            int size = input.Length;
            byte[] result = new byte[size];
            int packIdx = 0;
            while (size > 0)
            {
                byte[] packData = new byte[16];
                byte[] packRst = new byte[16];
                Array.Copy(input, packIdx * 16, packData, 0, (size > 16) ? 16 : size);
                Sm4OneRound(ctx.Key, packData, packRst);
                Array.Copy(packRst, 0, result, packIdx * 16, (size > 16) ? 16 : size);
                size -= 16;
                packIdx++;
            }
            // 处理数据对齐
            if (ctx.IsPadding && mode == 0)
            {
                result = Padding(result, 0);
            }
            // 返回
            return result;
        }

        public static byte[] Sm4CryptCbc(Sm4Context ctx, int mode, byte[] input)
        {
            // 处理数据对齐
            if (ctx.IsPadding && mode == 1)
            {
                input = Padding(input, 1);
            }
            // 处理数据
            int size = input.Length;
            List<byte> buffer = new List<byte>();
            if (mode == 1)
            {
                int packIdx = 0;
                // 初始化IV
                byte[] iv = new byte[16];
                random.NextBytes(iv);
                for (int i = 0; i < 16; i++)
                {
                    buffer.Add(iv[i]);
                }
                // 加密
                while (size > 0)
                {
                    byte[] packData = new byte[16];
                    byte[] packRound = new byte[16];
                    byte[] packRst = new byte[16];
                    // 对数据进行IV处理
                    Array.Copy(input, packIdx * 16, packData, 0, (size > 16) ? 16 : size);
                    for (int i = 0; i < 16; i++)
                    {
                        packRound[i] = (byte)(packData[i] ^ iv[i]);
                    }
                    // 加密
                    Sm4OneRound(ctx.Key, packRound, packRst);
                    // 更新IV
                    Array.Copy(packRst, 0, iv, 0, 16);
                    // 构建返回数据
                    for (int i = 0; i < 16; i++)
                    {
                        buffer.Add(packRst[i]);
                    }
                    // 移动到下一个数据包
                    size -= 16;
                    packIdx++;
                }
            }
            else
            {
                int packIdx = 1;
                size -= 16;
                // 初始化IV
                byte[] iv = new byte[16];
                byte[] iv0 = new byte[16];
                Array.Copy(input, 0, iv, 0, 16);
                // 解密
                while (size > 0)
                {
                    byte[] packData = new byte[16];
                    byte[] packRound = new byte[16];
                    byte[] packRst = new byte[16];
                    // 解密
                    Array.Copy(input, packIdx * 16, packData, 0, (size > 16) ? 16 : size);
                    Array.Copy(packData, 0, iv0, 0, 16);
                    Sm4OneRound(ctx.Key, packData, packRound);
                    // 对数据进行IV处理
                    for (int i = 0; i < 16; i++)
                    {
                        packRst[i] = (byte)(packRound[i] ^ iv[i]);
                    }
                    // 更新IV
                    Array.Copy(iv0, 0, iv, 0, 16);
                    // 构建返回数据
                    for (int i = 0; i < 16; i++)
                    {
                        buffer.Add(packRst[i]);
                    }
                    // 移动到下一个数据包
                    size -= 16;
                    packIdx++;
                }
            }
            // 处理数据对齐
            byte[] result = buffer.ToArray();
            if (ctx.IsPadding && mode == 0)
            {
                result = Padding(result, 0);
            }
            // 返回
            return result;
        }
    }
}
